﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using LayerEntity.Caja;
using LayerEntity.Persona;
using LayerEntity.Sistema;
using LayerEntity.Creditos;
using LayerLogic.Creditos;
using LayerLogic;
using LayerEntity.Producto;

namespace System2012.Creditos
{
    public partial class frmAnticipos : DevExpress.XtraEditors.XtraForm
    {
        private double EQUIVALE_SOLES;
        private double IMPORTE_PENDIENTE;
        private double MONTO_AMORTIZA;
        private int op_fp;
        private double TOT_EQUIVALE_SOLES;
        private double TOTAL_LISTA;
        private int varIdDireccion;
        /// <summary>
        /// TABLA QUE ALMACENA TODOS LOS PAGOS DE LAS CANCELACIONES
        /// </summary>
        DataTable dtbPagos = new DataTable("Pagos");
        /// <summary>
        /// Indica si estamos editanado o creando uno Nuevo
        /// 0: Nuevo Documento
        /// 1: Editando y Guardando
        /// </summary>
        int operacion = 0;
        string varIdCliente;
        public frmAnticipos()
        {
            InitializeComponent();
            if (!this.BGWTipDoc.IsBusy)
            {
                this.BGWTipDoc.RunWorkerAsync();
            }
            this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            InitEvents();
            RecControles(this);
            CabeceraPagos();
            this.gridControl1.DataSource = this.dtbPagos;
        }

        private void frmAnticipos_Load(object sender, EventArgs e)
        {

        }
        #region Cabeceras
       

        private void CabeceraPagos()
        {
            this.dtbPagos.Columns.Add(new DataColumn("Form_pago", typeof(string)));//F/Pago
            this.dtbPagos.Columns.Add(new DataColumn("Banco", typeof(string)));
            this.dtbPagos.Columns.Add(new DataColumn("Tarjeta", typeof(string)));
            this.dtbPagos.Columns.Add(new DataColumn("Nro_Operación", typeof(string)));//Nro/Operación
            this.dtbPagos.Columns.Add(new DataColumn("M", typeof(string)));
            this.dtbPagos.Columns.Add(new DataColumn("Importe", typeof(decimal)));//Importe(S/ | $)
            this.dtbPagos.Columns.Add(new DataColumn("Imp_Recibido", typeof(decimal)));//Imp.Recibido(S/.| $ )
            this.dtbPagos.Columns.Add(new DataColumn("Equivale", typeof(double)));//Equivale(S/.)
            this.dtbPagos.Columns.Add(new DataColumn("Vuelto", typeof(decimal)));//Vuelto(S/.| $)
            this.dtbPagos.Columns.Add(new DataColumn("idMoneda", typeof(int)));
            this.dtbPagos.Columns.Add(new DataColumn("idFormaPago", typeof(int)));
            this.dtbPagos.Columns.Add(new DataColumn("idBanco", typeof(int)));
            this.dtbPagos.Columns.Add(new DataColumn("idTarjeta", typeof(int)));
        }

        #endregion
        #region Desplazamientos
        private void PresionadoTeclas(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter || e.KeyCode == Keys.Down)
            {
              

                //desplazamientos en cacelaciones

                if (sender == this.txtDocCliente)
                {
                    this.txtFecha.Focus();
                    this.txtFecha.SelectAll();
                }

                if (sender == this.txtFecha)
                {
                    this.txtIdVendedor.Focus();
                    this.txtIdVendedor.SelectAll();
                }
                if (sender == this.txtIdVendedor)
                {
                    this.txtIdProducto.Focus();
                    this.txtIdProducto.SelectAll();
                }
                if (sender == this.txtIdProducto)
                {
                    this.cmbTipDoc.Focus();
                    this.cmbTipDoc.SelectAll();
                }
                if (sender == this.cmbTipDoc)
                {
                    this.txtSerie.Focus();
                    this.txtSerie.SelectAll();
                }
                if (sender == this.txtSerie)
                {
                    this.txtNroComprobante.Focus();
                    this.txtNroComprobante.SelectAll();
                }
                if (sender == this.txtNroComprobante)
                {
                    this.txtIdCaja.Focus();
                    this.txtIdCaja.SelectAll();
                }
                if (sender == this.txtIdCaja)
                {
                    this.cmdFormaPago.Focus();
                    this.cmdFormaPago.SelectAll();
                }
                

                if (sender == this.txtNroReferencia)
                {
                    if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                    {
                        this.cmbBanco.Focus();
                        this.cmbBanco.SelectAll();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                        {
                            this.cmbTarjeta.Focus();
                            this.cmbTarjeta.SelectAll();
                        }
                        else
                        {
                            if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never && this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
                            {
                                txtImporteCobrar.Focus();
                                txtImporteCobrar.SelectAll();
                            }

                        }
                    }
                }

                if (sender == this.txtNroOperacion)
                {
                    this.txtImporteCobrar.Focus();
                    this.txtImporteCobrar.SelectAll();
                }
                if (sender == this.txtImporteCobrar)
                {
                    this.txtImporteRecibido.Focus();
                    this.txtImporteRecibido.SelectAll();
                }
            }

            if (e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
            {
                if (sender == this.cmbTipDoc)
                {
                    this.txtSerie.Focus();
                    this.txtSerie.SelectAll();
                }
                if (sender == this.cmdFormaPago)
                {
                    this.cmbMoneda.Focus();
                    this.cmbMoneda.SelectAll();
                }
               
                if (sender == this.cmbMoneda)
                {
                    this.txtNroReferencia.Focus();
                    this.txtNroReferencia.SelectAll();
                }
                if (sender == this.cmbMoneda)
                {

                    if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                    {
                        this.cmbBanco.Focus();
                        this.cmbBanco.SelectAll();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                        {
                            this.cmbTarjeta.Focus();
                            this.cmbTarjeta.SelectAll();
                        }
                        else
                        {
                            if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never && this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
                            {
                                txtImporteCobrar.Focus();
                                txtImporteCobrar.SelectAll();
                            }

                        }
                    }
                    //this.txtNroReferencia.Focus();
                    //this.txtNroReferencia.SelectAll();
                }

                if (sender == this.cmbBanco)
                {
                    this.txtNroOperacion.Focus();
                    this.txtNroOperacion.SelectAll();
                }
                if (sender == this.cmbTarjeta)
                {
                    this.txtNroOperacion.Focus();
                    this.txtNroOperacion.SelectAll();
                }
            }
            if (e.KeyCode == Keys.Up)
            {
               

                if (sender == this.txtSerie)
                {
                    this.cmbTipDoc.Focus();
                    this.cmbTipDoc.SelectAll();
                }

                if (sender == this.txtNroComprobante)
                {
                    this.txtSerie.Focus();
                    this.txtSerie.SelectAll();
                }
                if (sender == this.txtNroReferencia)
                {
                    this.cmbMoneda.Focus();
                    this.cmbMoneda.SelectAll();
                }

                if (sender == this.txtNroOperacion)
                {
                    if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                    {
                        this.cmbBanco.Focus();
                        this.cmbBanco.SelectAll();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                        {
                            this.cmbTarjeta.Focus();
                            this.cmbTarjeta.SelectAll();
                        }
                    }
                }

                if (sender == this.txtImporteCobrar)
                {
                    if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never && this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
                    {
                        this.txtNroReferencia.Focus();
                        this.txtNroReferencia.SelectAll();
                    }
                    else
                    {
                        if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always || this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                        {
                            this.txtNroOperacion.Focus();
                            this.txtNroOperacion.SelectAll();
                        }
                       
                    }
                }
                if (sender == this.txtImporteRecibido)
                {
                    this.txtImporteCobrar.Focus();
                    this.txtImporteCobrar.SelectAll();
                }
            }
            if (e.KeyCode == Keys.Left)
            {
                if (sender == this.cmdFormaPago)
                {
                    this.txtIdProducto.Focus();
                    this.txtIdProducto.SelectAll();
                }
                if (sender == this.cmbMoneda)
                {
                    this.cmdFormaPago.Focus();
                    this.cmdFormaPago.SelectAll();
                }

                if (sender == this.cmbBanco)
                {
                    this.txtNroReferencia.Focus();
                    this.txtNroReferencia.SelectAll();
                }
                if (sender == this.cmbTarjeta)
                {
                    this.txtNroReferencia.Focus();
                    this.txtNroReferencia.SelectAll();
                }
            }
        }

        public void RecControles(Control control)
        {
            foreach (Control contHijo in control.Controls)
            {
                if (contHijo.HasChildren)
                {
                    this.RecControles(contHijo);
                }
                contHijo.KeyDown += new KeyEventHandler(PresionadoTeclas);
            }
        }

        #endregion
        #region Validaciones


        private bool validacionescajas()
        {
            bool res = false;
            if (this.txtSerie.Text == string.Empty)
            {
                XtraMessageBox.Show(this, "La serie del comprobante no ha sido generada  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                res = false;
            }
            else
            {
                if (this.txtNroComprobante.Text == string.Empty)
                {
                    XtraMessageBox.Show(this, "ro de comprobante no ha sido generado   ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    res = false;
                }
                else
                {
                    if (this.txtImporteCobrar.Text == string.Empty)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "El importe a cobrar esta vacio ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        if (this.txtMontoVuelto.Text == string.Empty)
                        {
                            res = false;
                            XtraMessageBox.Show(this, "Ingrese el monto recibido  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                            this.txtImporteRecibido.Focus();
                        }
                        else
                        {
                           
                                if (this.MONTO_VUELTO > 0)
                                {
                                    XtraMessageBox.Show(this, "el valor del vuelto no pude ser mayor a cero, \nverifique este corretamente ingresado  el importe recibido", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                                    res = false;
                                }
                                else
                                {
                                    if (this.txtImporteCobrar.Text.Length == 0)
                                    {
                                        res = false;
                                        XtraMessageBox.Show(this, "Ingrese el importe a cobrar", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                    else
                                    {
                                        if (double.Parse(this.txtImporteCobrar.Text) <= 0)
                                        {
                                            res = false;
                                            XtraMessageBox.Show(this, "Ingrese el importe a cobrar  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        }
                                        else
                                        {
                                            if (this.txtImporteRecibido.Text.Length == 0)
                                            {
                                                res = false;
                                                XtraMessageBox.Show(this, "Ingrese el importe a recibido  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                            }
                                            else
                                            {
                                                if (double.Parse(this.txtImporteRecibido.Text) <= 0)
                                                {
                                                    res = false;
                                                    XtraMessageBox.Show(this, "Ingrese el importe recibido  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                }
                                                else
                                                {
                                                    if (this.cmbMoneda.ItemIndex == -1)
                                                    {
                                                        res = false;
                                                        XtraMessageBox.Show(this, "SELECCIONE EL TIPO DE MONEDA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                        this.cmbMoneda.Focus();
                                                    }
                                                    else
                                                    {
                                                        if (this.cmdFormaPago.ItemIndex == -1)
                                                        {
                                                            res = false;
                                                            XtraMessageBox.Show(this, "SELECCIONE EL TIPO DE MONEDA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                            this.cmdFormaPago.Focus();
                                                        }
                                                        else
                                                        {
                                                            res = true;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                
                                //res=true;
                            }
                        }
                    }
                }
            }

            return res;
        }

        private bool validaPagos()
        {
            bool res = false;
            if (this.op_fp == 1)
            {
                if (this.txtNroOperacion.Text == string.Empty)
                {
                    res = false;
                    this.txtNroOperacion.Focus();
                    this.lblMsg.Text = "INGRESE EL NRO DE CHEQUE";
                }
                else
                {
                    res = true;
                    this.lblMsg.Text = "";
                }
            }
            else
            {
                if (this.op_fp == 2)
                {
                    if (this.txtNroOperacion.Text == string.Empty)
                    {
                        res = false;
                        this.txtNroOperacion.Focus();
                        this.lblMsg.Text = "INGRESE EL NRO DE OPERACIÓN";
                    }
                    else
                    {
                        res = true;
                        this.lblMsg.Text = "";
                    }
                }
                else
                {
                    if (this.op_fp == 4)
                    {
                        if (this.txtNroOperacion.Text == string.Empty)
                        {
                            res = false;
                            this.txtNroOperacion.Focus();
                            this.lblMsg.Text = ("INGRESE EL NRO DE OPERACIÓN");
                        }
                        else
                        {
                            res = true;
                            this.lblMsg.Text = ("");
                        }
                    }
                    else
                    {
                        if (this.MONTO_VUELTO > 0)
                        {
                            // XtraMessageBox.Show(this, "EL IMP.AMORTIZADO \n NO PUEDE SER MAYOR QUE EL \nIMPORTE A TOTAL PAGAR  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            XtraMessageBox.Show(this, "el valor del vuelto no pude ser mayor a cero, \nverifique este corretamente ingresado  el importe recibido",
                                "Información", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            res = false;
                        }
                        else
                        {
                            res = true;
                        }
                    }
                }
            }
            return res;
        }

        private bool ValidadcionesMovContado()
        {
            bool res = false;
            if (txtIdCaja.Text == string.Empty)
            {
                res = false;
                XtraMessageBox.Show(this, "No ha seleccionado ninguna caja destino ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtIdCaja.Focus();
            }
            else
            {
                if (txtSerie.Text == string.Empty)
                {
                    res = false;
                    XtraMessageBox.Show(this, "La serie del comprobante no ha sido generada  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    txtSerie.Focus();

                }
                else
                {
                    if (txtNroComprobante.Text == string.Empty)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "Nro de comprobante no ha sido generado  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        txtNroComprobante.Focus();

                    }
                    else
                    {
                        if (this.txtTotImporte.Text == string.Empty)
                        {
                            res = false;
                            XtraMessageBox.Show(this, "El importe TOTAL esta vacio  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        }
                        else
                        {
                            if (this.txtMontoVuelto.Text == string.Empty)
                            {
                                res = false;
                                XtraMessageBox.Show(this, "Ingrese el monto recibido ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                            }
                            else
                            {

                                if (double.Parse(txtTotImporte.Text) < double.Parse(txtImporteCobrar.Text))
                                {
                                    res = false;
                                    XtraMessageBox.Show(this, "OPERACION INCORRECTA \n\n"
                                            + "EL MONTO CANCELADO ES MENOR AL IMPORTE TOTAL A PAGAR", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Warning);


                                }
                                else
                                {

                                    res = true;

                                }

                            }
                        }
                    }
                }
            }
            return res;
        }

        private bool ValidaSelects()
        {
            bool res = false;
            if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
            {
                if (this.cmbBanco.ItemIndex == -1)
                {
                    res = false;
                    XtraMessageBox.Show(this, "NO HA SELECCIONADO NINGUN BANCO\nPARA REALIZAR ESTA OPERACION", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    this.cmbBanco.Focus();
                }
                else
                {
                    res = true;
                }
            }
            else
            {
                if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
                {
                    if (this.cmbTarjeta.ItemIndex == -1)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "NO HA SELECCIONADO\nNINGUNA TARJETA DE PAGO", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        this.cmbTarjeta.Focus();
                    }
                    else
                    {
                        res = true;
                    }
                }
                else
                {
                    if (this.cmbMoneda.ItemIndex == -1)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "SELECCIONE EL TIPO DE MONEDA", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.cmbMoneda.Focus();
                    }
                    else
                    {
                        if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never && this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Never)
                        {
                            res = true;
                        }
                        else
                        {
                            res = false;
                        }
                    }
                }
            }

            return res;
        }
        private bool ValidarNroComprobante()
        {
            bool res = false;
            if (this.txtSerie.Text != string.Empty && this.txtNroComprobante.Text != string.Empty)
            {
                if (int.Parse(this.txtSerie.Text) == 0)
                {
                    res = false;
                    this.txtSerie.Focus();
                }
                else
                {
                    if (int.Parse(this.txtNroComprobante.Text) == 0)
                    {
                        res = false;
                        this.txtNroComprobante.Focus();
                    }
                    else
                    {
                        res = true;
                    }
                }
            }
            else
            {
                this.txtSerie.Focus();
                res = false;
            }
            return res;
        }
        private bool ValidarForm()
        {
            bool res = true;
           
            if (txtCliente.Text == string.Empty)
            {
                res = false;
                XtraMessageBox.Show(this, "Seleccione un cliente para poder efectuar el Anticipo", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtCliente.Focus();
                txtCliente.SelectAll();
            }
            else
            {
                if (txtDocCliente.Text == string.Empty)
                {
                    res = false;
                    XtraMessageBox.Show(this, "Seleccione un cliente para poder efectuar el Anticipo", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtDocCliente.Focus();
                    txtDocCliente.SelectAll();
                }
                else
                {
                    if (txtIdVendedor.Text == string.Empty)
                    {
                        res = false;
                        XtraMessageBox.Show(this, "Seleccione el  responsable de la venta", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        txtIdVendedor.Focus();
                        txtIdVendedor.SelectAll();
                    }
                    else
                    {
                        if (txtIdProducto.Text == string.Empty)
                        {
                            res = false;
                            XtraMessageBox.Show(this, "Seleccione un producto referencial del Anticipo", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            txtIdProducto.Focus();
                            txtIdProducto.SelectAll();
                        }
                        
                    }
                }
            }
            return res;
        }
        private void HabilitarFP()
        {
            // cmbBanco.Properties.Columns.Clear();
            int IDFP = int.Parse(this.cmdFormaPago.EditValue.ToString());
            switch (IDFP)
            {
                case 7: //CHEQUE
                    this.ItemBanco.Size = new System.Drawing.Size(272, 24);
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;

                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Banco";
                    this.txtNroOperacion.Enabled = true;
                    this.op_fp = 1;
                    if (this.BGWBanco.IsBusy)
                    {
                        this.BGWBanco.RunWorkerAsync();
                    }
                    break;
                case 1: //DEPOSITO
                    this.ItemBanco.Size = new System.Drawing.Size(272, 24);
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Banco";
                    this.txtNroOperacion.Enabled = true;
                    if (this.BGWBanco.IsBusy)
                    {
                        this.BGWBanco.RunWorkerAsync();
                    }

                    this.op_fp = 2;
                    break;
                case 8: //EFECTIVO
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    // ItemTarjeta.Size = new System.Drawing.Size(282, 24);
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    // this.cmbBanco.Enabled = false;
                    this.ItemBanco.Text = "Caja";
                    this.txtNroOperacion.Enabled = false;
                    this.op_fp = 3;
                    if (this.BGWBanco.IsBusy)
                    {
                        this.BGWBanco.RunWorkerAsync();
                    }
                    //  cmbBanco.Properties.ValueMember = "id_caja";
                    //  cmbBanco.Properties.DisplayMember = "nombre";
                    break;

                case 6: //TARJETA DE CREDITO
                    // layoutControlItem10.Location = new Point(-100, -500);
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Size = new System.Drawing.Size(246, 24);
                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Tarjeta";
                    this.txtNroOperacion.Enabled = true;
                    if (this.BGWTarjetaCredito.IsBusy)
                    {
                        this.BGWTarjetaCredito.RunWorkerAsync();
                    }

                    break;
                case 5: //TARJETA DE DEBITO

                    this.ItemTarjeta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemBanco.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                    this.ItemNroOperacion.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                    this.ItemTarjeta.Size = new System.Drawing.Size(246, 24);
                    this.cmbBanco.Enabled = true;
                    this.ItemBanco.Text = "Tarjeta";
                    this.txtNroOperacion.Enabled = true;
                    if (this.BGWTarjetaCredito.IsBusy)
                    {
                        this.BGWTarjetaCredito.RunWorkerAsync();
                    }

                    this.op_fp = 4;
                    break;
                default:
                    this.op_fp = 5;
                    break;
            }
        }
        #endregion
        #region Busquedas
        private void SeleccionarVendedor()
        {
            Listados.frmListadoPersona f = new Listados.frmListadoPersona();
            f.ShowDialog();
            txtIdVendedor.Text = f.idPer;
            txtVendedor.Text = f.full_name;
        }
        private void SeleccionarProducto()
        {
             Listados.frmBusquedaProductos f = new Listados.frmBusquedaProductos();
            f.Opcion = 2;
            f.ShowDialog();
            if (f.data != null)
            {
                if (f.data[0] != null)
                {
                    txtProducto.Text = f.data[1].ToString();
                    txtIdProducto.Text = f.data[0].ToString();
                    varIdPrecio = int.Parse(f.data[10].ToString());
                    varIdUnimed =int.Parse( f.data[8].ToString());
                    varidLista = int.Parse(f.data[9].ToString());

                }
            }
        }
        private void SeleccionarCliente()
        {
            Persona.BuscarPersona b = new System2012.Persona.BuscarPersona(LayerEntity.Persona.EnumTipoPersona.Proveedor);
            b.ShowDialog();
            if (b.Estado)
            {
                IEPersona per = b.Persona;
                this.txtDocCliente.EditValue = per.NumeroDocumento;
                this.txtCliente.EditValue = per.RazonSocial;
                this.varIdCliente = per.IdPersona;
                EDireccion dir = per.GetAddress(b.IdAddressSelected);
                if (dir != null)
                {

                    varIdDireccion = dir.Item;
                    txtDirCliente.EditValue = dir.Direccion;
                    /* LayerEntity.Sistema.EUbigeo ubi = SystemUtils.RecordManagerCommonList.GetUbigeoByUbigeo(dir.Ubigeo);
                     if (ubi != null)
                     {
                         TxtUbigeo.EditValue = string.Concat(ubi.Ubigeo, "=>", ubi.ToString());
                     }*/
                }
            }
        }
        #endregion
        #region Gestion de Plantillas
        public string PLANTILLA;
        public string IMPRESORA;
        private void getPlantilla()
        {
            if (cmbTipDoc.EditValue != null)
            {
                ESistema obj = new ESistema();
                StringBuilder cadena = new StringBuilder();
                cadena.AppendFormat("where id_tranzaccion='{0}'",20);
                cadena.AppendFormat(" and  id_documento={0}", cmbTipDoc.EditValue);
                obj.Condicion = cadena.ToString();
                DataTable dtb = System2012.SystemUtils.RecordManagerCommonList.GetListaSeriesDocumento(obj);
                if (dtb.Rows.Count > 0)
                {
                    PLANTILLA = dtb.Rows[0]["plantilla"].ToString();
                    IMPRESORA = dtb.Rows[0]["impresora"].ToString();
                    txtSerie.Text = dtb.Rows[0]["serie"].ToString();
                    getCorrelativo();
                }
                else
                {
                    txtSerie.Text = null;
                    PLANTILLA = null;
                    IMPRESORA = null;
                }
            }
        }
        private void getCorrelativo()
        {
            ESeriesDocumento Es = new ESeriesDocumento();
            Es.Id_Tranzaccion = "20";
            Es.Id_Documento = int.Parse(cmbTipDoc.EditValue.ToString());
            Es.Serie = txtSerie.Text;
            Es.Id_Sucursal = 1;
            string correlativo = System2012.SystemUtils.CommonMaintenanceList.getCorrelativo(Es);
            txtNroComprobante.Text = correlativo.PadLeft(7, '0');
        }
        #endregion
        #region Eventos
        private void EditValueChanged(object sender, EventArgs e)
        {
            this.getPlantilla();
        }
        private void KeyPressInit(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                getCorrelativo();
            }
        }
       
        private void SerieLeave(object sender, EventArgs e)
        {
            string codigo = this.txtSerie.Text;
            while (codigo.Length < 4)
            {
                codigo = string.Format("0{0}", codigo);
            }
            this.txtSerie.Text = codigo;
        }
        private void SerieEnter(object sender, EventArgs e)
        {
            if (this.txtSerie.Text.Length > 0)
            {
                int codigo = int.Parse(this.txtSerie.Text);
                this.txtSerie.Text = string.Format("{0}", codigo);
            }
        }
        private void NroLeave(object sender, EventArgs e)
        {
            string codigo = this.txtNroComprobante.Text;
            while (codigo.Length < 7)
            {
                codigo = string.Format("0{0}", codigo);
            }
            this.txtNroComprobante.Text = codigo;
        }

        private void NroEnter(object sender, EventArgs e)
        {
            if (this.txtNroComprobante.Text.Length > 0)
            {
                int codigo = int.Parse(this.txtNroComprobante.Text);
                this.txtNroComprobante.Text = string.Format("{0}", codigo);
            }
        }
        private void DocCliente_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (this.txtDocCliente.Text != string.Empty)
                {
                    if (!BGWCliente.IsBusy) BGWCliente.RunWorkerAsync();
                }
                /*else
                {
                    SeleccionarCliente();
                }*/
            }
        }
        private void InitEvents()
        {
            this.cmbTipDoc.EditValueChanged += new EventHandler(this.EditValueChanged);
            this.cmbTipDoc.KeyPress += new KeyPressEventHandler(this.KeyPressInit);
            txtSerie.Leave += new EventHandler(this.SerieLeave);
            txtSerie.Enter += new EventHandler(this.SerieEnter);
            txtSerie.KeyPress += new KeyPressEventHandler(this.KeyPressInit);
            txtNroComprobante.Leave += new EventHandler(this.NroLeave);
            txtNroComprobante.Enter += new EventHandler(this.NroEnter);
            txtNroComprobante.KeyPress += new KeyPressEventHandler(this.KeyPressInit);
            txtDocCliente.KeyPress += new KeyPressEventHandler(DocCliente_KeyPress);
        }
        #endregion
        #region Calculos
        private void getAmortizacionMov()
        {
            string imp_amotiza = null;
            imp_amotiza = this.txtImporteCobrar.Text;
            if (imp_amotiza == string.Empty)
            {
                imp_amotiza = "0.0";
            }
            this.TOTAL_LISTA = 0.0;
            this.MONTO_AMORTIZA = double.Parse(imp_amotiza);
            double total_s = 0;
            double total_d = 0;
            for (int i = 0; i < this.dtbPagos.Rows.Count; i++)
            {
                if (this.dtbPagos.Rows[i]["M"].ToString() == "$")
                {
                    total_d += double.Parse(this.dtbPagos.Rows[i]["Importe"].ToString());
                }
                else
                {
                    total_s += double.Parse(this.dtbPagos.Rows[i]["Importe"].ToString());
                }
            }
            this.TOTAL_LISTA = total_s + total_d * double.Parse(this.txtTipoCambio.Caption);
            if (this.cmbMoneda.SelectedText == "$")// ejecutamos si es ua venta en dolares
            {
                this.EQUIVALE_SOLES = this.MONTO_AMORTIZA * double.Parse(this.txtTipoCambio.Caption);
                this.TOT_EQUIVALE_SOLES = this.TOTAL_LISTA + this.EQUIVALE_SOLES;

                this.IMPORTE_PENDIENTE =  (this.EQUIVALE_SOLES + this.TOTAL_LISTA);
                
            }
            else
            {
                this.EQUIVALE_SOLES = this.MONTO_AMORTIZA;
                this.IMPORTE_PENDIENTE = (this.EQUIVALE_SOLES + this.TOTAL_LISTA);
                this.TOT_EQUIVALE_SOLES = this.TOTAL_LISTA + this.EQUIVALE_SOLES;
               
            }
            StringBuilder cadena = new StringBuilder();
            cadena.AppendFormat(this.cmbMoneda.SelectedText +" {0} ", this.txtImporteCobrar.Text);
            cadena.AppendFormat("  Equivale en S/. : {0}", this.EQUIVALE_SOLES);
            this.lblMsg.Text = string.Format("PENDIENTE : {0}", this.IMPORTE_PENDIENTE);
            this.lblEquiVale.Text = cadena.ToString();// cmbMoneda.SelectedText + "  " + txtImporteCobrar.Text + "  ||  Equivale en S/. : " + EQUIVALE_SOLES;
        }


        private double MONTO_RECIBIDO;
        public double MONTO_VUELTO;
        private double MONTO_PAGAR;
        private void getImporteVuelto()
        {
            if (this.txtImporteCobrar.Text.Length > 0)
            {
                if (this.txtImporteRecibido.Text != string.Empty)
                {
                    this.MONTO_RECIBIDO = double.Parse(this.txtImporteRecibido.Text);
                    this.MONTO_PAGAR = double.Parse(this.txtImporteCobrar.Text);
                    if (this.MONTO_PAGAR > 0)
                    {
                        this.MONTO_VUELTO = this.MONTO_PAGAR - this.MONTO_RECIBIDO;
                        this.txtMontoVuelto.Text = this.MONTO_VUELTO.ToString();
                    }
                    else
                    {
                        if (this.MONTO_RECIBIDO > 0)
                        {
                            XtraMessageBox.Show(this, "Ingrese el Monto del Importe a Cobrar  ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            //return;
                        }
                        //txtImporteCobrar.Focus();
                    }
                }
            }
            else
            {
                XtraMessageBox.Show(this, "Ingrese el Importe a Cobrar ", "AVISO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.txtImporteCobrar.Focus();
            }
        }
        
        
        
        private void AddDetallePagos()
        {
            double vuelto = double.Parse(this.txtMontoVuelto.Text);
            String val_vuelto = "0.00";
            object idBanco;
            object idTarjeta;
            if (vuelto < 0)
            {
                val_vuelto = this.txtMontoVuelto.Text;
            }
            else
            {
                val_vuelto = "0.00";
            }
            String banco = "";
            if (this.ItemBanco.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility .Always)
            {
                banco = this.cmbBanco.Text;
                idBanco = this.cmbBanco.EditValue.ToString();
            }
            else
            {
                banco = "";
                idBanco = DBNull.Value;
            }
            String tarjeta = "";
            if (this.ItemTarjeta.Visibility == DevExpress.XtraLayout.Utils.LayoutVisibility.Always)
            {
                tarjeta = this.cmbTarjeta.Text;
                Console.Write(string.Format("TAREJATA :{0}", tarjeta));
                idTarjeta = this.cmbTarjeta.EditValue.ToString();
            }
            else
            {
                idTarjeta = DBNull.Value;// DBNull.Value.ToString();
                tarjeta = "";
            }
            
            DataRow r = this.dtbPagos.NewRow();
            r["Form_pago"] = this.cmdFormaPago.Text;
            r["Banco"] = banco;
            r["Tarjeta"] = tarjeta;
            r["Nro_Operación"] = this.txtNroOperacion.Text;
            r["M"] = this.cmbMoneda.Text;
            r["Importe"] = this.txtImporteCobrar.Text;
            r["Imp_Recibido"] = this.txtImporteRecibido.Text;
            r["Equivale"] = this.EQUIVALE_SOLES;
            r["Vuelto"] = val_vuelto;
            r["idMoneda"] = this.cmbMoneda.EditValue;
            r["idFormaPago"] = this.cmdFormaPago.EditValue;
            r["idBanco"] = idBanco;
            r["idTarjeta"] = idTarjeta;
            this.dtbPagos.Rows.Add(r);
        }
        double IMPORTE_TOTAL = 0.00;
        double IMPORTE_TOTAL_VUELTO = 0.00;
        double IMPORTE_TOTAL_RECIBIDO = 0.00;
        private int varidLista;
        private int varIdPrecio;
        private int varIdUnimed;
        private void Totales()
        {
            double importe_s = 0.00;
            double importe_d = 0.00;
            double imp_recibido_s = 0.00;
            double imp_recibido_d = 0.00;
            double imp_vuelto_s = 0.00;
            double imp_vuelto_d = 0.00;
            
            for (int i = 0; i < this.dtbPagos.Rows.Count; i++)
            {
                if (dtbPagos.Rows[i]["M"].ToString() == "$")
                {
                    imp_recibido_d += double.Parse(this.dtbPagos.Rows[i]["Imp_Recibido"].ToString());
                    importe_d += double.Parse(this.dtbPagos.Rows[i]["Importe"].ToString());
                    imp_vuelto_d += double.Parse(this.dtbPagos.Rows[i]["Vuelto"].ToString());
                }
                else
                {
                    imp_recibido_s += double.Parse(this.dtbPagos.Rows[i]["Imp_Recibido"].ToString());
                    importe_s += double.Parse(this.dtbPagos.Rows[i]["Importe"].ToString());
                    imp_vuelto_s += double.Parse(this.dtbPagos.Rows[i]["Vuelto"].ToString());
                }
            }
            IMPORTE_TOTAL_RECIBIDO = imp_recibido_s + imp_recibido_d * double.Parse(this.txtTipoCambio.Caption);
            IMPORTE_TOTAL_VUELTO = imp_vuelto_s + imp_vuelto_d * double.Parse(this.txtTipoCambio.Caption);
            IMPORTE_TOTAL = importe_s + importe_d * double.Parse(this.txtTipoCambio.Caption);

            this.txtTotImporte.Text = IMPORTE_TOTAL.ToString();
            this.txtImpRecibido_s.Text = IMPORTE_TOTAL_RECIBIDO.ToString();
            // txtImpRecibido_d.setText(format.FormatMoney(String.valueOf(imp_recibido_d)));
            this.txtTotalVuelto.Text = IMPORTE_TOTAL_VUELTO.ToString();
        }
        
        #endregion
        #region Mantenimientos
        private void SaveAnticipos()
        {
            ECreditos obCred = new ECreditos();
             EMovientoCaja Emov= new EMovientoCaja ();
            obCred.Id_anticipo = null;
            obCred.Item = this.varIdDireccion;
            obCred.IdPersona = varIdCliente;
            obCred.Facturado = "N";
            obCred.Glosa = txtGlosa.Text;
            obCred.Idusuario = "";
            obCred.Tipo_Anticipo = "F";
            obCred.Id_Moneda = int.Parse(cmbMoneda.EditValue.ToString());

            obCred.ItemDet = 0;
            obCred.Cantidad = 1;
            obCred.Id_estado = 1;
            obCred.IdPrecio = this.varIdPrecio;
            obCred.IdUnimed = varIdUnimed;
            obCred.IdProducto = txtIdProducto.Text;
            obCred.IdLista = varidLista;
            obCred.IsPrincipal = 1;

            obCred.Id_credito = "";
            obCred.Id_prodcredito = 0; ;
            obCred.Imp_recargo = 0;
            obCred.Imp_amortizacion = double.Parse(txtTotImporte.Text);
            obCred.Imp_cuota = double.Parse(txtTotImporte.Text);
            obCred.Imp_cuotacapital = double.Parse(txtTotImporte.Text);
            obCred.Imp_interes = 0.0;//tasa de interes
            obCred.Nro_cuotas = 1;
            obCred.Intervalo_cuota = 0;
            obCred.Mese_pago_interes = 1;
            obCred.Id_estado = 1;
            obCred.Facturado = "S";
            obCred.Id_anticipo = null;
            obCred.Id_sucursal_credito = 1;
            obCred.Imp_credito = double.Parse(txtTotImporte.Text);
            obCred.Idusuario = "";

            obCred.FecPago = DateTime.Parse(this.txtFecha.Text);
            obCred.GenerMora = "N";
            //obCred.FecRefinanciamiento = DateTime.Parse(DBNull.Value.ToString());
            obCred.ImpMora = 0;
            obCred.DiasGracia = 0;
            obCred.ImpAdicional = 0;
            obCred.NroLetra = "I-0";
            obCred.Fec_emision = DateTime.Parse(txtFecha.Text);
            obCred.FecVencimiento = DateTime.Parse(txtFecha.Text);
            

                Emov.Id_movimiento  =0;
	            Emov.Serie   =txtSerie.Text;       
	            Emov.Nro_comprobante=txtNroComprobante.Text ;
	            Emov.Id_caja_destino=int.Parse(txtIdCaja.Text);
	            Emov.Doc_referencia =txtNroReferencia.Text;
	            Emov.Importe_mora   =0;
	            Emov.Imp_movimiento =double.Parse(txtTotImporte.Text);
	            Emov.Glosa          =txtGlosa.Text;
	            Emov.Desacargo      ="N";
	            Emov.Imp_recibido   =double.Parse(txtImpRecibido_s.Text);
	            Emov.Imp_vuelto     =double.Parse(txtTotalVuelto.Text);
	            Emov.Idusuario         ="";
	            Emov.Id_sucursal_mov   =1;
                Emov.Id_cobrador = txtIdVendedor.Text;// txtIdCaja.Text;
	            Emov.Id_tranzaccion_mov="20";
	            Emov.Fecha_mov     =DateTime.Parse(txtFecha.Text);    
	            Emov.Id_estado      =1;
	            Emov.Nro_operacion  =txtNroOperacion.Text;
                Emov.Id_documento_mov = int.Parse(cmbTipDoc.EditValue.ToString());

            object[] result = System2012.SystemUtils.RecordManagerCreditos.MantenimientoAnticipos(obCred,Emov, this.operacion == 0 ? EnumOperaciones.Insertar : EnumOperaciones.Actualizar);
            MessageBox.Show(this, result[0].ToString());
        }
        #endregion
        #region Consultas

        private bool validaCodigoProducto(string codigo)
        {
            bool res = true;
            EProducto obj = new EProducto();
            obj.descripcion = string.Format("where id_producto= '{0}'", codigo);
            DataTable dtbProd = SystemUtils.RecodManajerproducto.GetListaProductos(obj);
            if (dtbProd.Rows.Count > 0)
            {
                res = false;
            }
            return res;
        }
        #endregion
        private void BGWMoneda_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetMoneda();
        }

        private void BGWFormaPago_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetFormaPago("S");
        }

        private void BGWBanco_DoWork(object sender, DoWorkEventArgs e)
        {
            ECaja objC = new ECaja();
            objC.Condicion = "";
            e.Result = System2012.SystemUtils.RecordmanagerCaja.GetListaCaja(objC);
        }

        private void BGWTarjetaCredito_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetTarjetaCredito();
        }

        private void BGWTarjetaCredito_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbTarjeta.Properties.DataSource = e.Result;
        }

        private void BGWMoneda_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbMoneda.Properties.DataSource = e.Result;
            if (!this.BGWBanco.IsBusy)
            {
                cmbMoneda.EditValue = 1;
                this.BGWBanco.RunWorkerAsync();
            }
        }

        private void BGWBanco_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbBanco.Properties.DataSource = e.Result;
            if (!this.BGWTarjetaCredito.IsBusy)
            {
                this.BGWTarjetaCredito.RunWorkerAsync();
            }
        }

        private void cmdFormaPago_EditValueChanged(object sender, EventArgs e)
        {
            this.HabilitarFP();
        }

        private void BGWTipDoc_DoWork(object sender, DoWorkEventArgs e)
        {
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetDocument(2);
        }

        private void BGWTipDoc_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.cmbTipDoc.Properties.DataSource = e.Result;
            if (!this.BGWFormaPago.IsBusy)
            {
                    cmbTipDoc.EditValue = 24;
                    BGWFormaPago.RunWorkerAsync();

            }
        }

        private void BGWFormaPago_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            this.cmdFormaPago.Properties.DataSource = e.Result;
            if (!this.BGWMoneda.IsBusy)
            {
                this.BGWMoneda.RunWorkerAsync();
                cmdFormaPago.EditValue = 8;
            }
        }

       

        private void txtIdVendedor_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                SeleccionarVendedor();
            }

        }

        private void txtIdVendedor_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(this.txtIdVendedor.Text))
                {
                    if (!BGWListPersonal.IsBusy) BGWListPersonal.RunWorkerAsync();
                }
                else
                {
                    SeleccionarVendedor();
                }
            }
        }

        private void BGWListPersonal_DoWork(object sender, DoWorkEventArgs e)
        {
            ESistema obj = new ESistema();
            StringBuilder cadena = new StringBuilder();
            cadena.AppendFormat("where id_persona='{0}' ", txtIdVendedor.Text);
            obj.Condicion = cadena.ToString();
            e.Result = System2012.SystemUtils.RecordManagerCommonList.GetListadoPersonal(obj);
        }

        private void BGWListPersonal_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataTable dtbPersonal = (DataTable)e.Result;
            if (dtbPersonal.Rows.Count > 0)
            {

                txtVendedor.Text = dtbPersonal.Rows[0]["fullname_persona"].ToString();
            }
            else
            {
                SeleccionarVendedor();
            }
        }

        private void txtIdProducto_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                SeleccionarProducto();
            }
        }

        private void txtIdCaja_KeyUp(object sender, KeyEventArgs e)
        {
            
        }

        private void txtIdCaja_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (!string.IsNullOrEmpty(this.txtIdCaja.Text))
                {
                    if (!BGEListCaja.IsBusy) BGEListCaja.RunWorkerAsync();
                }
                else
                {
                    //SeleccionarVendedor();
                }
            }
        }

        private void BGEListCaja_DoWork(object sender, DoWorkEventArgs e)
        {
            ECaja objC = new ECaja();
            objC.Condicion = string.Format("where id_caja = {0}", txtIdCaja.Text);
            e.Result = System2012.SystemUtils.RecordmanagerCaja.GetListaCaja(objC);
        }

        private void BGEListCaja_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataTable dtbC = (DataTable)e.Result;
            if (dtbC.Rows.Count > 0)
            {
                txtCaja.Text = dtbC.Rows[0]["nombre"].ToString();
            }
        }

        private void BGWCliente_DoWork(object sender, DoWorkEventArgs e)
        {

            ESistema obj = new ESistema();
            StringBuilder cadena = new StringBuilder();
            cadena.AppendFormat("where id_persona='{0}' ",txtDocCliente.Text);
            cadena.AppendFormat("or doc_persona='{0}' ", txtDocCliente.Text);
            obj.Condicion = cadena.ToString();
            e.Result = System2012.SystemUtils.RecordManagerPersona.GetListaClientes(obj);
        }

        private void BGWCliente_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            DataTable dtbP = (DataTable)e.Result;
            if (dtbP.Rows.Count > 0)
            {
                this.txtFecha.Focus();
                // txtVendedor.Text = dtbPersonal.Rows[0]["fullname_persona"].ToString();
            }
            else
            {
                if (this.txtDocCliente.Text != string.Empty)
                {
                    this.SeleccionarCliente();
                }
                else
                {
                    txtCliente.Focus();
                }
            }
        }

        private void txtDocCliente_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                SeleccionarCliente();
            }
        }

        private void txtImporteCobrar_TextChanged(object sender, EventArgs e)
        {
            this.getAmortizacionMov();
        }

        private void txtImporteRecibido_TextChanged(object sender, EventArgs e)
        {
            this.getImporteVuelto();
        }

        private void txtImporteRecibido_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (this.validaPagos() == true)
                {
                    if (this.txtImporteCobrar.Text != string.Empty)
                    {
                        if (this.validacionescajas() == true)
                        {
                            if (this.ValidaSelects() == true)
                            {
                                this.AddDetallePagos();
                                this.txtImporteCobrar.Text = "0.0";
                                this.txtImporteRecibido.Text = "0.0";
                                this.Totales();
                               
                            }
                        }
                    }
                }
            }
        }
        private void Ok()
        {
            if (XtraMessageBox.Show(this, "Está a punto de confirmar el Movimiento de caja\n" +
                                    "Confirmación Requerida ?", "Confirmación", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                SaveAnticipos();
                this.Close();
            }
            else
            {
                return;
            }
        }
        private void btnGrabar_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (ValidadcionesMovContado() == true)
            {
                if (ValidarNroComprobante())
                {
                    if (ValidarForm())
                    {
                        Ok();
                    }
                }
            }
        }

        private void memoExEdit1_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtTotImporte_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void txtIdProducto_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (validaCodigoProducto(txtIdProducto.Text))
                {
                    SeleccionarProducto();
                }
            }
        }

       
    }
}